
package com.control;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dominio.Usuario;
import com.jdbc.BDManagement;
import com.servicio.FactoryService;
import com.servicio.SeguridadI;


public class LoginServlet extends HttpServlet {

    
    private SeguridadI seguridad;     
    

    @Override
    public void init() throws ServletException {
        super.init();
        try {
			seguridad = FactoryService.getSeguridadService("default");
		} catch (SQLException e) {
			e.printStackTrace();
		}
    }
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String usuario = request.getParameter("usuario");
        String password = request.getParameter("password");
        
        Usuario uObject = seguridad.validarUsuario(new Usuario(usuario, password));
        
        if(uObject.getMensageError()!= null){
            request.setAttribute("errorMensaje",uObject.getMensageError());
            
            
            this.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
            //request.getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
        }else{
        	HttpSession session = request.getSession(true);
        	session.setAttribute("user", usuario);
        	request.getSession().setAttribute("usuario",uObject);
            this.getServletContext().getRequestDispatcher("/principal.jsp").forward(request, response);

        }
    }
    
    

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

   
    @Override
    public String getServletInfo() {
        return "Short description";
    }
}
